package com.winit.openapi.apiadapter.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.user.command.QueryTokenCommand;

@Controller
public class GetTokenAdapteController extends BaseController {

    @Resource
    private UmsUserService umsUserService;

    /**
     * 老ERPgetToken接口,接口返回格式：
     * {
     *     "code": 0,
     *     "data": "89435277FA3BA272DE795559998E-",
     *     "msg": "成功"
     *  }
     *  与user.getToken格式不一样，不能直接调用
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getToken")
    public String getToken(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 用户名必填
        ValidateUtil.validNotNull(json, "userName");
        ValidateUtil.validMaxLength(json, "userName", 64, true);
        // 密码必填
        ValidateUtil.validNotNull(json, "passWord");
        ValidateUtil.validMaxLength(json, "passWord", 64, true);

        String userName = json.getString("userName");
        String passWord = json.getString("passWord");

        QueryTokenCommand queryTokenCommand = new QueryTokenCommand();
        queryTokenCommand.setUserName(userName);
        queryTokenCommand.setPassword(passWord);
        String token = umsUserService.getToken(queryTokenCommand);

        if (StringUtils.isBlank(token)) {

            throw new ApiException(ErrorCode.USERNAME_OR_PASSWORD_INVALID);
        }
        responseMsg.setData(token);

        //此处必须返回API_ADAPTED_SUCCESS，这样会对错误码进行适配，将字符型错误码转为ERP的整形
        return API_ADAPTED_SUCCESS;

    }

}
